package cn.wu.reggie.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.wu.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;


    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        // 1 指定存放文件的目录 如果不存在就创建
        File dirPath = new File(path);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }

        // 2 获取文件的名字 生成uuid 拼接后缀名
        String filename = IdUtil.fastUUID()
                + "."
                + FileUtil.extName(file.getOriginalFilename());// uuid+"."+jpg

        // 3 文件拷贝
        file.transferTo(new File(dirPath, filename));

        // 4 返回文件名
        return R.success(filename);
    }

    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws IOException {
        // 1 获取输入流
        FileInputStream is = new FileInputStream(path + name);

        // 2 获取输出流 对拷
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);

        // 3 关闭流
        os.close();
        is.close();
    }
}
